package net.wangds.utils;

import java.util.Date;

public class ChineseCitizenIdCardUtils {

    public static boolean validate(String no)
    {
        // 对身份证号进行长度等简单判断
        if (no == null || no.length() != 18 || !no.matches("\\d{17}[0-9X]"))
        {
            return false;
        }
        // 1-17位相乘因子数组
        int[] factor = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
        // 18位随机码数组
        char[] random = "10X98765432".toCharArray();
        // 计算1-17位与相应因子乘积之和
        int total = 0;
        for (int i = 0; i < 17; i++)
        {
            total += Character.getNumericValue(no.charAt(i)) * factor[i];
        }
        // 判断随机码是否相等
        return random[total % 11] == no.charAt(17);
    }

    /**
     * 从身份证获得性别.
     * @param idNo 身份证号.
     *             <p>必须18位</p>
     * @return 身份证号的性别代码.
     * <p><ul><li>0-女</li><li>1-男</li></ul></p>
     */
    public static int getSex(String idNo){
        int res = 0;

        if(idNo.length()==18){
            res = Integer.parseInt(idNo.substring(16, 17))%2;
        }

        return res;
    }

    public static Date getBirthday(String idNo){
        Date birthday = null;
        if(idNo.length()==18){
            String date = idNo.substring(6,14);
            System.out.println(date);
            birthday = DateUtils.parse(date, "yyyyMMdd", true);
        }
        return birthday;
    }

    public static void main(String[] args){
        String id = "210104198012272510";
        System.out.println(validate(id));
        System.out.println(getSex(id)==1?"男":"女");
        System.out.println(getBirthday(id));
        System.out.println(DateUtils.toDefaultDateStr(getBirthday(id)));
    }

}
